<?php
namespace App\Api;

use PhalApi\Api;
use App\Domain\Vip as Domain_Vip;
header('Access-Control-Allow-Origin: *'); // 允许所有域名访问
header('Content-Type: application/json');
/**
 * 会员中心
 */

class Vip extends Api {

	public function getRules() {
        return array(
            'myVip' => array(
				'uid' => array('name' => 'uid', 'type' => 'int', 'desc' => '用户ID'),
				'token' => array('name' => 'token', 'type' => 'string', 'desc' => '用户token'),
			),
            
            'buyVip' => array(
				'uid' => array('name' => 'uid', 'type' => 'int', 'desc' => '用户ID'),
				'token' => array('name' => 'token', 'type' => 'string', 'desc' => '用户token'),
				'vipid' => array('name' => 'vipid', 'type' => 'string', 'desc' => 'VIP ID'),
			),
            'getAliOrderh5' => array(
				'uid' => array('name' => 'uid', 'type' => 'int', 'desc' => '用户ID'),
                'token' => array('name' => 'token', 'type' => 'string', 'desc' => '用户token'),
				'vipid' => array('name' => 'vipid', 'type' => 'int', 'desc' => 'VIP ID'),
				'money' => array('name' => 'money', 'type' => 'string', 'desc' => '金额'),
			),
            'getAliOrder' => array(
				'uid' => array('name' => 'uid', 'type' => 'int', 'desc' => '用户ID'),
                'token' => array('name' => 'token', 'type' => 'string', 'desc' => '用户token'),
				'vipid' => array('name' => 'vipid', 'type' => 'int', 'desc' => 'VIP ID'),
				'money' => array('name' => 'money', 'type' => 'string', 'desc' => '金额'),
			),
			'getWxOrder' => array( 
				'uid' => array('name' => 'uid', 'type' => 'int', 'desc' => '用户ID'),
                'token' => array('name' => 'token', 'type' => 'string', 'desc' => '用户token'),
				'vipid' => array('name' => 'vipid', 'type' => 'string',  'desc' => 'VIP ID'),
				'money' => array('name' => 'money', 'type' => 'string', 'desc' => '金额'),
			),
			'getIosOrder' => array(
				'uid' => array('name' => 'uid', 'type' => 'int', 'desc' => '用户ID'),
                'token' => array('name' => 'token', 'type' => 'string', 'desc' => '用户token'),
				'vipid' => array('name' => 'vipid', 'type' => 'string',  'desc' => 'VIP ID'),
				'money' => array('name' => 'money', 'type' => 'string', 'desc' => '金额'),
			),
			'getPaypalOrder' => array(
				'uid' => array('name' => 'uid', 'type' => 'int', 'desc' => '用户ID'),
                'token' => array('name' => 'token', 'type' => 'string', 'desc' => '用户token'),
				'vipid' => array('name' => 'vipid', 'type' => 'string',  'desc' => 'VIP ID'),
				'money' => array('name' => 'money', 'type' => 'string', 'desc' => '金额'),
			),
			'updatePaymentStatus' => array( 
				'uid' => array('name' => 'uid', 'type' => 'int', 'min' => 1, 'require' => true, 'desc' => '用户ID'),
				'token' => array('name' => 'token', 'type' => 'string', 'require' => true, 'desc' => '用户token'),
				'orderid' => array('name' => 'orderid', 'type' => 'string',  'require' => true, 'desc' => '订单号'),
				'money' => array('name' => 'money', 'type' => 'string', 'require' => true, 'desc' => '充值金额'),
				'nonce' => array('name' => 'nonce', 'type' => 'string', 'require' => true, 'desc' => 'paypal支付订单号'),
				'time' => array('name' => 'time', 'type' => 'string', 'desc' => '时间戳'),
			),
        );
	}
	
	/**
     * braintree回调处理
     * @desc 用于braintree回调处理
     * @return int code 操作码，0表示成功
     * @return string msg 提示信息
     */
	public function updatePaymentStatus() {
		$rs = array('code' => 0, 'msg' => '', 'info' => array());
		 
        $uid=\App\checkNull($this->uid);
		$token=\App\checkNull($this->token);
		$orderid=\App\checkNull($this->orderid);
		$money=\App\checkNull($this->money);
		$nonce=\App\checkNull($this->nonce);
		$time=\App\checkNull($this->time);
		
		
		// $now=time();
        // if($now-$time>300){
            // $rs['code']=1001;
            // $rs['msg']=\PhalApi\T('参数错误');
            // return $rs;
        // }
		
		$domain = new Domain_Vip();
		$info = $domain->updatePaymentStatus($uid,$nonce,$orderid,$money);
	
		if($info==1003){
			$rs['code'] = 1003;
			$rs['msg'] = \PhalApi\T('订单信息有误，请重新提交');
			return $rs;
		}
		
		

		$rs['msg']=\PhalApi\T('操作成功');
		
        return $rs;
    }
	
    /**
     * 我的VIP
     * @desc 用于获取我的VIP
     * @return int code 操作码，0表示成功
     * @return array info 
     * @return string info[0].isvip 是否VIP，0否1是  
     * @return string info[0].endtime 到期时间
     * @return array info[0].list vip列表  
     * @return string info[0].list[].id   
     * @return string info[0].list[].name 名称  
     * @return string info[0].list[].coin 钻石数
     * @return string info[0].list[].coin_money CNY
	 * @return string info[0].aliapp_partner 支付宝合作者身份ID
	 * @return string info[0].aliapp_seller_id 支付宝帐号	
	 * @return string info[0].aliapp_key 支付宝密钥PKCS8
	 * @return string info[0].wx_appid 微信APPID
     * @return array info[0].paylist 支付方式列表
     * @return string info[0].paylist[].id ali支付宝，wx微信，apple苹果
     * @return string info[0].paylist[].name 名称
     * @return string info[0].paylist[].thumb 图标
     * @return string msg 提示信息
     */
	public function myVip() {
        $rs = array('code' => 0, 'msg' => '', 'info' => array());
        
        $uid=\App\checkNull($this->uid);
		$token=\App\checkNull($this->token);
        
        $checkToken=\App\checkToken($uid,$token);
		if($checkToken==700){
			$rs['code'] = $checkToken;
			$rs['msg'] = \PhalApi\T('您的登陆状态失效，请重新登陆！');
			return $rs;
		}
        
        
        $domain = new Domain_Vip();
        
		$list=$domain->getVip();
        
        foreach($list as $k=>$v){
            unset($v['length']);
            unset($v['coin_apple']);
            unset($v['list_order']);
            
            $list[$k]=$v;
        }
        
		$info=$domain->myVip($uid);
        
        $info['list']=$list;
        
        $configpri=\App\getConfigPri();
        $aliapp_switch=$configpri['aliapp_switch'];
        $wx_switch=$configpri['wx_switch'];
        $ios_switch=$configpri['ios_switch'];
        $paypal_switch=$configpri['paypal_switch'];
		$aliapp_switch_h5=$configpri['aliapp_switch_h5'];
        
        $paylist=[];
        
        $paylist[]=[
                'id'=>'coin',
                'name'=>\PhalApi\T('余额支付'),
                'thumb'=>\App\get_upload_path("/static/app/pay/coin.png"),
            ];
        
        if($aliapp_switch){
            $paylist[]=[
                'id'=>'ali',
                'name'=>\PhalApi\T('支付宝支付'),
                'thumb'=>\App\get_upload_path("/static/app/pay/ali.png"),
            ];
        }
        
        if($wx_switch){
            $paylist[]=[
                'id'=>'wx',
                'name'=>\PhalApi\T('微信支付'),
                'thumb'=>\App\get_upload_path("/static/app/pay/wx.png"),
            ];
        }
        
		if($paypal_switch){
            $paylist[]=[
                'id'=>'paypal',
                'name'=>\PhalApi\T('Paypal支付'),
                'thumb'=>\App\get_upload_path("/static/app/pay/paypal.png"),
            ];
        }
		
		if($aliapp_switch_h5){
            $paylist[]=[
                'id'=>'alih5',
                'name'=>\PhalApi\T('支付宝支付'),
                'thumb'=>\App\get_upload_path("/static/app/pay/ali.png"),
            ];
        }
        
		
		
        /* if($ios_switch && $type!=1){
            $paylist[]=[
                'id'=>'apple',
                'name'=>'苹果支付',
                'thumb'=>get_upload_path("/static/app/pay/apple.png"),
            ];
        } */
        
        $info['paylist'] =$paylist;
		
		$info['aliapp_partner']=$aliapp_switch==1?$configpri['aliapp_partner']:'';
		$info['aliapp_seller_id']=$aliapp_switch==1?$configpri['aliapp_seller_id']:'';
		$info['aliapp_key']=$aliapp_switch==1?$configpri['aliapp_key']:'';
        
		$info['wx_appid']=$wx_switch==1?$configpri['wx_appid']:'';
		
		
		$info['paypal_sandbox']=$paypal_switch==1?$configpri['paypal_sandbox']:'0';
		$info['sandbox_clientid']=$paypal_switch==1?$configpri['sandbox_clientid']:'';
		$info['product_clientid']=$paypal_switch==1?$configpri['product_clientid']:'';
        
        $rs['info'][0]=$info;
        
        return $rs;
	}

    /**
     * 钻石购买VIP
     * @desc 用于使用钻石购买VIP
     * @return int code 操作码，0表示成功
     * @return array info 
     * @return string info[0].isvip 是否VIP，0否1是  
     * @return string info[0].endtime 到期时间
     * @return string msg 提示信息
     */
	public function buyVip() {
        $rs = array('code' => 0, 'msg' => '', 'info' => array());
        
        $uid=\App\checkNull($this->uid);
		$token=\App\checkNull($this->token);
		$vipid=\App\checkNull($this->vipid);
        
        if($uid<1 || $token=='' || $vipid<1 ){
            $rs['code'] = 1001;
			$rs['msg'] = \PhalApi\T('信息错误');
			return $rs;
        }
        
        $checkToken=\App\checkToken($uid,$token);
		if($checkToken==700){
			$rs['code'] = $checkToken;
			$rs['msg'] = \PhalApi\T('您的登陆状态失效，请重新登陆！');
			return $rs;
		}
        
        
        $domain = new Domain_Vip();
        
        
		$result=$domain->buyVip($uid,$vipid);
        
        return $result;
	}
    
	/* 获取订单号 */
	protected function getOrderid($uid){
		$orderid=$uid.'_'.date('YmdHis').rand(100,999);
		return $orderid;
	}

	/**
	 * 微信购买VIP
	 * @desc 用于 微信购买VIP 获取订单号
	 * @return int code 操作码，0表示成功
	 * @return array info 
	 * @return string info[0] 支付信息
	 * @return string msg 提示信息
	 */
	public function getWxOrder() {
		$rs = array('code' => 0, 'msg' => '', 'info' => array());
		
		$uid=\App\checkNull($this->uid);
		$token=\App\checkNull($this->token);
		$vipid=\App\checkNull($this->vipid);
		$money=\App\checkNull($this->money);

		if(!$uid || !$vipid || $money<=0){
			$rs['code']=1002;
			$rs['msg']=\PhalApi\T('信息错误');
			return $rs;
		}
		
        $checkToken=\App\checkToken($uid,$token);
		if($checkToken==700){
			$rs['code'] = $checkToken;
			$rs['msg'] = \PhalApi\T('您的登陆状态失效，请重新登陆！');
			return $rs;
		}
        
		$configpri = \App\getConfigPri(); 
		$configpub = \App\getConfigPub(); 

		 //配置参数检测
		if($configpri['wx_appid']== "" || $configpri['wx_mchid']== "" || $configpri['wx_key']== ""){
			$rs['code'] = 1002;
			$rs['msg'] = \PhalApi\T('微信未配置');
			return $rs;					 
		}

		$type=2;
        $orderid=$this->getOrderid($uid);
		
		$orderinfo=array(
			"uid"=>$uid,
			"money"=>$money,
			"orderno"=>$orderid,
			"type"=>$type,
			"status"=>0,
			"addtime"=>time()
		);

		
		$domain = new Domain_Vip();
		$info = $domain->setOrder($vipid,$orderinfo);
		if($inf['code']!=0){
            return $info;
		}

			 
		$noceStr = md5(rand(100,1000).time());//获取随机字符串
		$time = time();
			
		$paramarr = array(
			"appid"       =>   $configpri['wx_appid'],
			"body"        =>    \PhalApi\T("购买VIP"),
			"mch_id"      =>    $configpri['wx_mchid'],
			"nonce_str"   =>    $noceStr,
			"notify_url"  =>    $configpub['site_url'].'/appapi/vipback/notify_wx',
			"out_trade_no"=>    $orderid,
			"total_fee"   =>    $money*100, 
			"trade_type"  =>    "APP"
		);
		$sign = $this -> sign($paramarr,$configpri['wx_key']);//生成签名
		$paramarr['sign'] = $sign;
		$paramXml = "<xml>";
		foreach($paramarr as $k => $v){
			$paramXml .= "<" . $k . ">" . $v . "</" . $k . ">";
		}
		$paramXml .= "</xml>";
			 
		$ch = curl_init ();
		@curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查  
		@curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在  
		@curl_setopt($ch, CURLOPT_URL, "https://api.mch.weixin.qq.com/pay/unifiedorder");
		@curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		@curl_setopt($ch, CURLOPT_POST, 1);
		@curl_setopt($ch, CURLOPT_POSTFIELDS, $paramXml);
		@$resultXmlStr = curl_exec($ch);
		if(curl_errno($ch)){
			//print curl_error($ch);
			file_put_contents('./vipwxpay.txt',date('y-m-d H:i:s').' 提交参数信息 ch:'.json_encode(curl_error($ch))."\r\n",FILE_APPEND);
		}
		curl_close($ch);

		$result2 = $this->xmlToArray($resultXmlStr);
        
        if($result2['return_code']=='FAIL'){
            $rs['code']=1005;
			$rs['msg']=$result2['return_msg'];
            return $rs;	
        }
		$time2 = time();
		$prepayid = $result2['prepay_id'];
		$sign = "";
		$noceStr = md5(rand(100,1000).time());//获取随机字符串
		$paramarr2 = array(
			"appid"     =>  $configpri['wx_appid'],
			"noncestr"  =>  $noceStr,
			"package"   =>  "Sign=WXPay",
			"partnerid" =>  $configpri['wx_mchid'],
			"prepayid"  =>  $prepayid,
			"timestamp" =>  $time2
		);
		$paramarr2["sign"] = $this -> sign($paramarr2,$configpri['wx_key']);//生成签名
		
		$rs['info'][0]=$paramarr2;
		return $rs;			
	}		
	
	/**
	* sign拼装获取
	*/
	protected function sign($param,$key){
		$sign = "";
		foreach($param as $k => $v){
			$sign .= $k."=".$v."&";
		}
		$sign .= "key=".$key;
		$sign = strtoupper(md5($sign));
		return $sign;
	
	}
	/**
	* xml转为数组
	*/
	protected function xmlToArray($xmlStr){
		$msg = array(); 
		$postStr = $xmlStr; 
		$msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); 
		return $msg;
	}	
	
	/**
	 * 支付宝H5支付
	 * @desc 用于支付宝H5支付 获取订单号
	 * @return int code 操作码，0表示成功
	 * @return array info 
	 * @return string info[0].orderid 订单号
	 * @return string msg 提示信息
	 */
	public function getAliOrderh5() {
		$rs = array('code' => 0, 'msg' => '', 'info' => array());
		
		$uid=\App\checkNull($this->uid);
		$token=\App\checkNull($this->token);
		$vipid=\App\checkNull($this->vipid);
		$money=\App\checkNull($this->money);

		if(!$uid || !$vipid || $money<=0){
			$rs['code']=1002;
			$rs['msg']=\PhalApi\T('信息错误');
			return $rs;
		}
        
        $checkToken=\App\checkToken($uid,$token);
		if($checkToken==700){
			$rs['code'] = $checkToken;
			$rs['msg'] = \PhalApi\T('您的登陆状态失效，请重新登陆！');
			return $rs;
		}
        
		$type=5;
		$orderid=$this->getOrderid($uid);
        $orderid=$orderid."_1";
		$orderinfo=array(
			"uid"=>$uid,
			"money"=>$money,
			"orderno"=>$orderid,
			"type"=>$type,
			"status"=>0,
			"addtime"=>time()
		);
		
		$domain = new Domain_Vip();

		$info = $domain->setOrder($vipid,$orderinfo);
		if($inf['code']!=0){
            return $info;
		}
		
		$configpub = \App\getConfigPub();
		$viplist=$domain->getVip();
        $vipinfo=[];
        
        foreach($viplist as $k=>$v){
            if($v['id']==$vipid){
                $vipinfo=$v;
                break;
            }
        }
		
		$rs['info'][0]['orderid']=$orderid;
		$body=\PhalApi\T('购买');
		$WIDsubject=\PhalApi\T('购买VIP');
		$rs['info'][0]['href']=$configpub['site_url'].'/wxpay/pay.php?body='.$body.$vipinfo['name'].'VIP&total_amount='.$money.'&WIDout_trade_no='.$orderid.'&WIDsubject='.$WIDsubject;
		return $rs;
	}
		
	/**
	 * 支付宝支付
	 * @desc 用于支付宝支付 获取订单号
	 * @return int code 操作码，0表示成功
	 * @return array info 
	 * @return string info[0].orderid 订单号
	 * @return string msg 提示信息
	 */
	public function getAliOrder() {
		$rs = array('code' => 0, 'msg' => '', 'info' => array());
		
		$uid=\App\checkNull($this->uid);
		$token=\App\checkNull($this->token);
		$vipid=\App\checkNull($this->vipid);
		$money=\App\checkNull($this->money);

		if(!$uid || !$vipid || $money<=0){
			$rs['code']=1002;
			$rs['msg']=\PhalApi\T('信息错误');
			return $rs;
		}
        
        $checkToken=\App\checkToken($uid,$token);
		if($checkToken==700){
			$rs['code'] = $checkToken;
			$rs['msg'] = \PhalApi\T('您的登陆状态失效，请重新登陆！');
			return $rs;
		}
        
		$type=1;
		$orderid=$this->getOrderid($uid);
        
		$orderinfo=array(
			"uid"=>$uid,
			"money"=>$money,
			"orderno"=>$orderid,
			"type"=>$type,
			"status"=>0,
			"addtime"=>time()
		);
		
		$domain = new Domain_Vip();

		$info = $domain->setOrder($vipid,$orderinfo);
		if($inf['code']!=0){
            return $info;
		}
		
		$rs['info'][0]['orderid']=$orderid;
		return $rs;
	}		

	/**
	 * 苹果支付
	 * @desc 用于苹果支付 获取订单号
	 * @return int code 操作码，0表示成功
	 * @return array info 
	 * @return string info[0].orderid 订单号
	 * @return string msg 提示信息
	 */
	public function getIosOrder() {
		$rs = array('code' => 0, 'msg' => '', 'info' => array());
		
		$uid=\App\checkNull($this->uid);
		$token=\App\checkNull($this->token);
		$vipid=\App\checkNull($this->vipid);
		$money=\App\checkNull($this->money);

		if(!$uid || !$vipid || $money<=0){
			$rs['code']=1002;
			$rs['msg']=\PhalApi\T('信息错误');
			return $rs;
		}
        
        $checkToken=\App\checkToken($uid,$token);
		if($checkToken==700){
			$rs['code'] = $checkToken;
			$rs['msg'] = \PhalApi\T('您的登陆状态失效，请重新登陆！');
			return $rs;
		}
        
        $type=3;
        $orderid=$this->getOrderid($uid);

		$configpri = \App\getConfigPri(); 
		
		$orderinfo=array(
			"uid"=>$uid,
			"money"=>$money,
			"orderno"=>$orderid,
			"type"=>$type,
			"status"=>0,
			"addtime"=>time(),
			"ambient"=>$configpri['ios_sandbox']
		);
		
		$domain = new Domain_Vip();
		$info = $domain->setOrder($vipid,$orderinfo);
		if($inf['code']!=0){
            return $info;
		}

		$rs['info'][0]['orderid']=$orderid;
		return $rs;
	}		
	
	/**
	 * Paypal支付
	 * @desc 用于Paypal支付 获取订单号
	 * @return int code 操作码，0表示成功
	 * @return array info 
	 * @return string info[0].orderid 订单号
	 * @return string msg 提示信息
	 */
	public function getPaypalOrder() {
		$rs = array('code' => 0, 'msg' => '', 'info' => array());
		
		$uid=\App\checkNull($this->uid);
		$token=\App\checkNull($this->token);
		$vipid=\App\checkNull($this->vipid);
		$money=\App\checkNull($this->money);

		if(!$uid || !$vipid || $money<=0){
			$rs['code']=1002;
			$rs['msg']=\PhalApi\T('信息错误');
			return $rs;
		}
        
        $checkToken=\App\checkToken($uid,$token);
		if($checkToken==700){
			$rs['code'] = $checkToken;
			$rs['msg'] = \PhalApi\T('您的登陆状态失效，请重新登陆！');
			return $rs;
		}
        
        $type=4;
        $orderid=$this->getOrderid($uid);

		$configpri = \App\getConfigPri(); 
		
		$orderid=$orderid.'_2'; //代表Vip充值
		
		$orderinfo=array(
			"uid"=>$uid,
			"money"=>$money,
			"orderno"=>$orderid,
			"type"=>$type,
			"status"=>0,
			"addtime"=>time(),
			"ambient"=>$configpri['paypal_pattern_braintree']
		);
		
		$domain = new Domain_Vip();
		$info = $domain->setOrder($vipid,$orderinfo);
		if($inf['code']!=0){
            return $info;
		}

		$rs['info'][0]['orderid']=$orderid;
		return $rs;
	}		
	
	
    
}
